package pers.qianyu.diytomcat.util;

import cn.hutool.core.io.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
import pers.qianyu.diytomcat.catalina.*;
import pers.qianyu.diytomcat.constants.*;

import java.io.*;
import java.util.*;

/**
 * @author mizzle rain
 * @date 2021-01-07 17:45
 */
public class WebXmlUtil {
    private static Map<String, String> mimeTypeMapping = new HashMap<>();

    public static synchronized String getMimeType(String extName) {
        if (mimeTypeMapping.isEmpty()) {
            initMimeType();
        }
        String mimeType = mimeTypeMapping.get(extName);
        if (Objects.isNull(mimeType)) {
            mimeType = "text/html";
        }
        return mimeType;
    }

    private static void initMimeType() {
        String xml = FileUtil.readUtf8String(Locations.WEB_XML);
        Document document = Jsoup.parse(xml);
        Elements elements = document.select("mime-mapping");
        for (Element element : elements) {
            String extension = element.select("extension").first().text();
            String mimeType = element.select("mime-type").first().text();
            mimeTypeMapping.put(extension, mimeType);
        }
    }

    public static String getWelcomeFile(Context context) {
        String xml = FileUtil.readUtf8String(Locations.WEB_XML);
        Document document = Jsoup.parse(xml);
        Element welcomeFileList = document.select("welcome-file-list").first();
        Elements elements = welcomeFileList.select("welcome-file");
        for (Element element : elements) {
            File file = FileUtil.file(context.getDocBase(), element.text());
            if (file.exists()) {
                return file.getName();
            }
        }
        return "index.html";
    }

    public static int getSessionTimeout() {
        try {
            String xml = FileUtil.readUtf8String(Locations.WEB_XML);
            Document document = Jsoup.parse(xml);
            Elements elements = document.select("session-config session-timeout");
            if (elements.isEmpty()) {
                return 30;
            }
            return Integer.parseInt(elements.first().text());
        } catch (IORuntimeException | NumberFormatException e) {
            return 30;
        }
    }
}
